package Day2025_01_13.Day2025_01_14;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Demo_01_Text {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请用户输入一个你要查找的路径.");
        String rootpath = scanner.next();
        File rootfile = new File(rootpath);
        if (!rootfile.exists()) {
            System.out.println("您输入的路径不存在.");
            return;
        }
        if (!rootfile.isDirectory()) {
            System.out.println("您输入的不是一个目录.");
            return;
        }
        System.out.println("请输入您要查找的字符串.");
        String keyWord = scanner.next();
        if (keyWord == null || keyWord.isEmpty()) {
            System.out.println("您输入的字符串格式错误.");
            return;
        }
        scan(rootfile, keyWord);
    }

    private static void scan(File rootfile, String keyWord) throws IOException {
        File[] files = rootfile.listFiles();
        if (files.length == 0) return;
        for (File file : files) {
            if (file.isFile()) {
                String filename = file.getName();
                if (filename.contains(keyWord)) {
                    System.out.println("找到文件:" + file.getCanonicalPath()
                            + ", 找到关键字: " + keyWord);
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("是否删除文件(Y/N)");
                    String key = scanner.next();
                    if (key.toLowerCase().equals("y")) {
                        file.delete();
                        System.out.println("删除成功.");
                    }
                }
            } else {
                scan(file, keyWord);
            }
        }
    }
}
